<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Article;
use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    //get.admin/article
    public function index()
    {
        $data = Article::orderBy('art_id','desc')->paginate(10);
        return view('admin/article/index',compact('data'));
    }

    public function edit($art_id)
    {
        $data = (new Category())->tree();
        $field = Article::find($art_id);
        return view('admin/article/edit',compact('data','field'));
    }

    public function update($art_id)
    {
        $input = Input::except('_token','_method');
        $rs = Article::where('art_id',$art_id)->update($input);
        if($rs){
            return redirect('admin/article');
        }else{
            return back()->with('error','文章修改失败,请稍后重试');
        }
    }
    //get.admin/article/create
    public function create()
    {
        $data = (new Category)->tree();
        return view('admin/article/add',compact('data'));
    }
    //post.admin/article
    public function store()
    {
        $input = Input::except('_token');
        $input['art_time'] = time();
        if(!$input['art_thumb']){
            $input['art_thumb']='style/images/default.jpg';
        }
        $rules = [
            'art_title'=>'required',
            'art_content'=>'required',

        ];
        $message = [
            'art_title.required'=>'文章标题不能为空!',
            'art_content.required'=>'文章内容不能为空!',
        ];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $rs = Article::create($input);
            if($rs){
                return redirect('admin/article');
            }else{
                return back()->with('error','数据填写失败,请稍后重试');
            }
        }else{
            return back()->withErrors($validator);
        }
    }
    public function destroy($art_id)
    {
        $rs = Article::where('art_id',$art_id)->delete();
        if($rs){
            $data = [
                'status'=>0,
                'msg'=>'文章删除成功!'
            ];
        }else{
            $data= [
                'status'=>1,
                'msg'=>'文章删除失败,请稍后重试!'
            ];
        }
        return $data;
    }
}
